# encoding: utf-8
import subprocess
from multiprocessing import Process, current_process
from typing import Optional
import os, time

from apps.log import LOGGER
from apps.db import Sqlite3cls

"""
// TaskMessage: 参数
type TaskMessage struct {
    TaskName     string
	TaskLogId    string
	Path         string
	Status       int
	IsSuccess    int
	GitX         utils.GitXParams
	PreCommandX  utils.CommandXParams
	PostCommandX utils.CommandXParams
	Result       string
	CommitId     string
}
"""

"""
self, args, bufsize=-1, executable=None,
    stdin=None, stdout=None, stderr=None,
    preexec_fn=None, close_fds=True,
    shell=False, cwd=None, env=None, universal_newlines=None,
    startupinfo=None, creationflags=0,
    restore_signals=True, start_new_session=False,
    pass_fds=(), *, encoding=None, errors=None, text=None

"""


class RunCmd:
    def __init__(self, task, running_work):
        """

        :param task: 任务
        :param task_list: 任务列表
        :param running_work: 正在运行的任务(全局对象)
        """
        self.task = task

        self.running_work = running_work
        self.pre_command_status = -1
        self.post_command_status = -1

    def run(self, cmd):
        """ 运行命令 """

        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             universal_newlines=True)
        p.wait(self.task.get("timeout"))

        if p.stdout is not None:
            result_stdout = p.stdout.readlines()  # 从子进程 p 的标准输出中读取所有行，并储存在一个list对象中
        else:
            result_stdout = []

        if p.stderr is not None:
            result_stderr = p.stderr.readlines()  # 从子进程 p 的标准输出中读取所有行，并储存在一个list对象中
            if result_stderr:
                LOGGER.info(f"执行异常, 状态码:{p.returncode}, msg:{result_stderr}")
                return result_stdout, result_stderr
        else:
            result_stderr = []

        """
        for line in result_lines:
            print(line.strip())
        """
        LOGGER.info(f"状态码:{p.returncode}")

        return result_stdout, result_stderr

    def pre_command(self):
        "前置命令"
        precmd = self.task.get('pre_ommand', None)
        self.pre_command_status = 0
        if precmd:
            return self.run(precmd)

    def post_command(self):
        "后置命令"
        post_md = self.task.get('post_ommand', None)
        self.post_command_status = 0
        if post_md:
            return self.run(post_md)

    def finish(self):
        """ 清除正在运行的任务 """

        if self.pre_command_status == 0 and self.post_command_status == 0:
            key = self.task.get("task_name", None)
            current_work = self.running_work.get(key, None)
            if current_work:
                self.running_work.pop(key)

                with Sqlite3cls() as sql:
                    rid= int(self.task.get("id"))
                    res= sql.task_delete(rid)
                    LOGGER.info(msg=f"完成任务:{current_work}, res:{res}")
